<template>
  <div class="announcement-management-container">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>公告管理</h2>
          <p>发布和管理系统公告</p>
        </div>
        <div class="page-actions">
          <el-button type="primary" @click="showAddAnnouncementDialog">
            <el-icon><Plus /></el-icon> 发布公告
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 公告筛选 -->
    <el-card class="filter-card">
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="公告标题">
            <el-input
              v-model="filterForm.title"
              placeholder="输入标题关键词"
              clearable
              @keyup.enter="handleFilter"
              @clear="handleFilter"
            />
          </el-form-item>
          <el-form-item label="公告类型">
            <el-select
              v-model="filterForm.type"
              placeholder="选择公告类型"
              clearable
              @change="handleFilter"
            >
              <el-option 
                v-for="category in categories" 
                :key="category.id" 
                :label="category.name" 
                :value="category.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="filterForm.status"
              placeholder="选择状态"
              clearable
              @change="handleFilter"
            >
              <el-option label="已发布" :value="1" />
              <el-option label="草稿" :value="0" />
              <el-option label="已过期" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <!-- 公告列表 -->
    <el-card class="announcement-list-card">
      <div v-loading="listLoading">
        <el-table
          :data="announcementList"
          border
          style="width: 100%"
          @row-click="handleRowClick"
        >
          <el-table-column prop="id" label="ID" width="80" sortable />
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
          <el-table-column label="类型" width="120">
            <template #default="scope">
              <el-tag :type="getAnnouncementTypeColor(scope.row.categoryId || scope.row.category_id)">
                {{ getAnnouncementTypeText(scope.row.categoryId || scope.row.category_id) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getAnnouncementStatusColor(scope.row.status)">
                {{ getAnnouncementStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="发布时间" width="180" sortable>
            <template #default="scope">
              {{ scope.row.startTime || scope.row.start_time }}
            </template>
          </el-table-column>
          <el-table-column label="过期时间" width="180">
            <template #default="scope">
              {{ scope.row.endTime || scope.row.end_time }}
            </template>
          </el-table-column>
          <el-table-column label="阅读量" width="100" sortable>
            <template #default="scope">
              {{ scope.row.readCount || scope.row.read_count || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.stop="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                v-if="scope.row.status === 0"
                type="success"
                size="small"
                @click.stop="handlePublish(scope.row)"
              >发布</el-button>
              <el-button
                v-if="scope.row.status === 1"
                type="warning"
                size="small"
                @click.stop="handleUnpublish(scope.row)"
              >下架</el-button>
              <el-button
                type="danger"
                size="small"
                @click.stop="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <!-- 空数据展示 -->
      <el-empty v-if="announcementList.length === 0 && !listLoading" description="暂无公告数据" />
    </el-card>
    
    <!-- 添加/编辑公告对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '发布公告' : '编辑公告'"
      width="700px"
      @close="resetDialogForm"
    >
      <el-form
        ref="announcementFormRef"
        :model="announcementForm"
        :rules="announcementRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="announcementForm.type" placeholder="请选择公告类型" style="width: 100%">
            <el-option 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" prop="date_range">
          <el-date-picker
            v-model="announcementForm.date_range"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="10"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="announcementForm.status">
            <el-radio :label="1">立即发布</el-radio>
            <el-radio :label="0">保存为草稿</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="置顶" prop="is_top">
          <el-switch v-model="announcementForm.is_top" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ dialogType === 'add' ? '发布' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="公告详情"
      width="700px"
    >
      <div v-if="currentAnnouncement" class="announcement-detail">
        <div class="announcement-detail-header">
          <h3>{{ currentAnnouncement.title }}</h3>
          <div class="announcement-meta">
            <span class="announcement-time">发布时间：{{ currentAnnouncement.startTime || currentAnnouncement.start_time }}</span>
            <span class="announcement-type">
              <el-tag size="small" :type="getAnnouncementTypeColor(currentAnnouncement.categoryId || currentAnnouncement.category_id)">
                {{ getAnnouncementTypeText(currentAnnouncement.categoryId || currentAnnouncement.category_id) }}
              </el-tag>
            </span>
            <span class="announcement-views">阅读量：{{ currentAnnouncement.readCount || currentAnnouncement.read_count || 0 }}</span>
          </div>
        </div>
        <div class="announcement-content">
          <p v-html="formatContent(currentAnnouncement.content)"></p>
        </div>
        <div class="announcement-footer">
          <span>有效期：{{ currentAnnouncement.startTime || currentAnnouncement.start_time }} 至 {{ currentAnnouncement.endTime || currentAnnouncement.end_time }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, View } from '@element-plus/icons-vue'
import { 
  getAdminAnnouncementList, 
  createAnnouncement, 
  updateAnnouncement, 
  deleteAnnouncement, 
  changeAnnouncementStatus,
  getAnnouncementCategories
} from '@/api/announcement'

// 列表数据
const announcementList = ref([])
const listLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 公告分类数据
const categories = ref([])

// 筛选表单
const filterForm = reactive({
  title: '',
  type: '',
  status: '',
  date_range: []
})

// 对话框表单
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const announcementFormRef = ref(null)
const announcementForm = reactive({
  id: '',
  title: '',
  type: 0,
  content: '',
  date_range: [],
  publish_time: '',
  expire_time: '',
  status: 1,
  is_top: false
})

// 表单验证规则
const announcementRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  date_range: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于 10 个字符', trigger: 'blur' }
  ]
}

const submitting = ref(false)

// 详情对话框
const detailVisible = ref(false)
const currentAnnouncement = ref(null)

// 获取公告类型文本
const getAnnouncementTypeText = (type) => {
  if (type === undefined || type === null) {
    return '未知类型'
  }
  const category = categories.value.find(c => c.id === type)
  return category ? category.name : '未知类型'
}

// 获取公告类型颜色
const getAnnouncementTypeColor = (type) => {
  if (type === undefined || type === null) {
    return 'info'
  }
  // 根据类型设置不同颜色
  switch (parseInt(type)) {
    case 1: return 'primary'  // 系统通知
    case 2: return 'warning'  // 维修通知
    case 3: return 'success'  // 活动通知
    case 4: return 'danger'   // 安全通知
    default: return 'info'    // 其他
  }
}

// 获取公告状态文本
const getAnnouncementStatusText = (status) => {
  switch (status) {
    case 0: return '草稿'
    case 1: return '已发布'
    case 2: return '已过期'
    default: return '未知状态'
  }
}

// 获取公告状态颜色
const getAnnouncementStatusColor = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

// 格式化内容
const formatContent = (content) => {
  if (!content) return ''
  return content.replace(/\n/g, '<br>')
}

// 获取公告列表
const fetchAnnouncements = async (params) => {
  listLoading.value = true
  
  try {
    // 调用真实API
    const response = await getAdminAnnouncementList(params)
    
    if (response.code === 200) {
      announcementList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取公告列表失败')
      announcementList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取公告列表失败', error)
    ElMessage.error('获取公告列表失败，请重试')
    announcementList.value = []
    total.value = 0
  } finally {
    listLoading.value = false
  }
}

// 获取公告分类
const fetchCategories = async () => {
  try {
    const response = await getAnnouncementCategories()
    if (response.code === 200) {
      categories.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取公告分类失败')
    }
  } catch (error) {
    console.error('获取公告分类失败', error)
    ElMessage.error('获取公告分类失败，请重试')
  }
}

// 处理筛选
const handleFilter = () => {
  // 重置到第一页
  currentPage.value = 1
  
  // 构建查询参数
  let params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    title: filterForm.title || undefined,
    // 将type改为categoryId
    categoryId: filterForm.type || undefined,
    status: filterForm.status !== undefined ? filterForm.status : undefined
  }
  
  // 处理日期范围
  if (filterForm.date_range && filterForm.date_range.length === 2) {
    // 将date_range[0]改为startTime
    params.startTime = filterForm.date_range[0]
    // 将date_range[1]改为endTime
    params.endTime = filterForm.date_range[1]
  }
  
  // 调用获取公告列表方法
  fetchAnnouncements(params)
}

// 重置筛选
const resetFilter = () => {
  filterForm.title = ''
  filterForm.type = undefined
  filterForm.status = undefined
  filterForm.date_range = []
  
  // 重置筛选后立即获取数据
  handleFilter()
}

// 处理分页大小变更
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAnnouncements()
}

// 处理页码变更
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAnnouncements()
}

// 显示添加公告对话框
const showAddAnnouncementDialog = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  
  // 复制数据到表单
  announcementForm.id = row.id
  announcementForm.title = row.title
  // 兼容后端返回的categoryId或category_id
  announcementForm.type = row.categoryId || row.category_id
  announcementForm.content = row.content
  announcementForm.status = row.status
  // 兼容后端返回的isTop或is_top
  announcementForm.is_top = row.isTop === 1 || row.is_top === 1
  
  // 设置日期范围，兼容后端返回的startTime/start_time和endTime/end_time
  const startTime = row.startTime || row.start_time
  const endTime = row.endTime || row.end_time
  if (startTime && endTime) {
    announcementForm.date_range = [startTime, endTime]
  }
  
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  await announcementFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    
    try {
      // 准备提交数据（使用驼峰命名法，与后端API匹配）
      const formData = {
        title: announcementForm.title,
        categoryId: announcementForm.type,  // 从category_id改为categoryId
        content: announcementForm.content,
        status: announcementForm.status,
        isTop: announcementForm.is_top ? 1 : 0  // 从is_top改为isTop
      }
      
      // 处理日期范围
      if (announcementForm.date_range && announcementForm.date_range.length === 2) {
        formData.startTime = announcementForm.date_range[0]  // 从start_time改为startTime
        formData.endTime = announcementForm.date_range[1]    // 从end_time改为endTime
      }
      
      let response
      
      if (dialogType.value === 'add') {
        // 创建新公告
        response = await createAnnouncement(formData)
      } else {
        // 更新公告
        response = await updateAnnouncement(announcementForm.id, formData)
      }
      
      if (response.code === 200) {
        const successMsg = dialogType.value === 'add' ? '公告发布成功' : '公告更新成功'
        ElMessage.success(successMsg)
        dialogVisible.value = false
        fetchAnnouncements()
      } else {
        ElMessage.error(response.message || '操作失败')
      }
    } catch (error) {
      console.error('提交公告失败', error)
      ElMessage.error('操作失败，请重试')
    } finally {
      submitting.value = false
    }
  })
}

// 重置对话框表单
const resetDialogForm = () => {
  announcementFormRef.value?.resetFields()
  announcementForm.id = ''
  announcementForm.title = ''
  announcementForm.type = 0
  announcementForm.content = ''
  announcementForm.date_range = []
  announcementForm.publish_time = ''
  announcementForm.expire_time = ''
  announcementForm.status = 1
  announcementForm.is_top = false
}

// 处理发布
const handlePublish = async (row) => {
  ElMessageBox.confirm(
    `确定要发布《${row.title}》这篇公告吗？`,
    '发布确认',
    {
      confirmButtonText: '确定发布',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      // 直接发送状态值1，而不是 { status: 1 }
      const response = await changeAnnouncementStatus(row.id, 1) 
      
      if (response.code === 200) {
        ElMessage.success('公告已发布')
        fetchAnnouncements() // 重新加载数据
      } else {
        ElMessage.error(response.message || '发布失败')
      }
    } catch (error) {
      console.error('发布公告失败', error)
      ElMessage.error('发布失败，请重试')
    }
  }).catch(() => {})
}

// 处理下架
const handleUnpublish = async (row) => {
  ElMessageBox.confirm(
    `确定要下架《${row.title}》这篇公告吗？`,
    '下架确认',
    {
      confirmButtonText: '确定下架',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 直接发送状态值0，而不是 { status: 0 }
      const response = await changeAnnouncementStatus(row.id, 0)
      
      if (response.code === 200) {
        ElMessage.success('公告已下架')
        fetchAnnouncements() // 重新加载数据
      } else {
        ElMessage.error(response.message || '下架失败')
      }
    } catch (error) {
      console.error('下架公告失败', error)
      ElMessage.error('下架失败，请重试')
    }
  }).catch(() => {})
}

// 处理删除
const handleDelete = async (row) => {
  ElMessageBox.confirm(
    `确定要删除《${row.title}》这篇公告吗？此操作不可恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(async () => {
    try {
      const response = await deleteAnnouncement(row.id)
      
      if (response.code === 200) {
        ElMessage.success('公告已删除')
        fetchAnnouncements() // 重新加载数据
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除公告失败', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {})
}

// 处理行点击
const handleRowClick = (row) => {
  currentAnnouncement.value = row
  detailVisible.value = true
}

// 组件挂载时获取列表
onMounted(() => {
  fetchCategories()
  fetchAnnouncements()
})
</script>

<style scoped>
.announcement-management-container {
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #1a237e, #283593);
  color: white;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 24px;
}

.page-title p {
  margin: 8px 0 0;
  opacity: 0.8;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.filter-form {
  width: 100%;
}

.announcement-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 公告详情样式 */
.announcement-detail {
  padding: 0 20px;
}

.announcement-detail-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.announcement-detail-header h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: bold;
}

.announcement-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  color: #909399;
  font-size: 14px;
}

.announcement-content {
  margin-bottom: 20px;
  line-height: 1.8;
  color: #303133;
}

.announcement-footer {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  color: #909399;
  font-size: 14px;
}

@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .page-actions {
    margin-top: 15px;
    width: 100%;
  }
  
  .page-actions .el-button {
    width: 100%;
  }
  
  .filter-form {
    display: flex;
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .el-date-picker {
    width: 100% !important;
  }
}
</style> 